package cn.holy.app.xcddt.ui.activity.archive

import android.content.ClipboardManager
import android.content.Context
import android.media.MediaPlayer
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.OrientationHelper
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.forEach
import androidx.recyclerview.widget.RecyclerView
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.R.id.top_bar
import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.app.GlideApp
import cn.holy.app.xcddt.domain.ProcessItem
import cn.holy.app.xcddt.domain.RecordBean
import cn.holy.app.xcddt.domain.RecordCheckBean
import cn.holy.app.xcddt.net.callback.LoadingCallback
import cn.holy.app.xcddt.repository.RecordRepository
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import cn.holy.app.xcddt.ui.activity.record.RecordActivity
import cn.holy.app.xcddt.utils.HDateUtils
import cn.holy.app.xcddt.utils.toImageUrl
import cn.jzvd.JZVideoPlayerStandard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.util.QMUIViewHelper
import com.qmuiteam.qmui.widget.QMUIItemViewsAdapter
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.yanzhenjie.album.Album
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import kotlinx.android.synthetic.main.activity_record_detail.*
import javax.inject.Inject


/**
 * Created by xionghao on 2018/3/1.
 */
@Route(path = "/app/archives/detail")
class ArchiveDetailActivity : BaseActivity() {

    @Inject
    lateinit var recordRep: RecordRepository
    private val photos: ArrayList<String> = ArrayList()
    private val medias: ArrayList<String> = ArrayList()

    private val checks: ArrayList<RecordCheckBean> = ArrayList()

    private var commonAdapter: CommonAdapter<String>? = null
    private var checkAdapter: CommonAdapter<RecordCheckBean>? = null

    private var mediaPlayer: MediaPlayer? = null
    private lateinit var clipboardManager: ClipboardManager

    override fun initData() {
        clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val recordBean = intent.getSerializableExtra("archive") as RecordBean
        tv_upload_name.text = "巡查人：" + recordBean.record_username
        tv_message.text = recordBean.message
        tv_address.text = recordBean.address
        tv_status.text = recordBean.status_label
        tv_record_no.text = "案卷编号：" + recordBean.record_no
        tv_record_12319.text = "12319编号：" + recordBean.task_num
        tv_message.setOnLongClickListener {
            clipboardManager.text = recordBean.message
            showToast("成功复制案卷信息到剪切板")
            return@setOnLongClickListener  true
        }
        tv_record_no.setOnLongClickListener {
            clipboardManager.text = recordBean.record_no
            showToast("成功复制案卷编号到剪切板")
            return@setOnLongClickListener  true
        }
        tv_record_12319.setOnLongClickListener {
            clipboardManager.text = recordBean.task_num
            showToast("成功复制12319编号到剪切板")
            return@setOnLongClickListener  true
        }
        tv_time.text = "上传时间：" + HDateUtils.dateToStrLong(recordBean.created_at)

        audio_content.visibility = if (TextUtils.isEmpty(recordBean.audio)) View.GONE else View.VISIBLE

        audio_content.setOnClickListener {
            if (mediaPlayer != null && mediaPlayer!!.isPlaying) {
                mediaPlayer!!.stop()
            } else {
                mediaPlayer = MediaPlayer()
                mediaPlayer?.setDataSource(recordBean.audio)
                mediaPlayer?.prepare()
                mediaPlayer?.start()
            }
        }
        val layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        photo_list.layoutManager = (layoutManager)
        if (recordBean.photos != null) {
            photos.clear()

            recordBean.photos?.forEach { it ->
                photos.add(it.toImageUrl())
            }
        }
        if (recordBean.medias != null) {
            medias.clear()

            recordBean.medias?.forEach { it ->
                medias.add(it.toImageUrl())
            }
        }
        if (recordBean.checks != null) {
            recordBean.checks?.forEach { item ->
                checks.clear()
                checks.add(item)
            }
        }
        val layoutManager2 = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        check_container.layoutManager = layoutManager2


        val layoutManager3 = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        medias_photo_list.layoutManager = layoutManager3
        medias_photo_list.visibility = if (medias.size > 0) View.VISIBLE else View.GONE

        var commonAdapter2 = object : CommonAdapter<String>(this, R.layout.layout_photo_item_list, medias) {

            override fun convert(holder: ViewHolder, path: String, position: Int) {
                val photo = holder.getView<ImageView>(R.id.iv_thumb)

                GlideApp.with(this@ArchiveDetailActivity).load(path).placeholder(R.mipmap.loading).centerCrop().into(photo)
                photo.setOnClickListener {
                    Album.gallery(this@ArchiveDetailActivity)
                            .checkedList(medias)
                            .requestCode(1001) // 请求码，会在listener中返回。
                            .checkable(false) // 是否有浏览时的选择功能。
                            .onResult { requestCode, result ->
                            }
                            .onCancel { requestCode, result -> }

                            .start() // 千万不要忘记调用start()方法。
                }
            }
        }
        medias_photo_list.adapter = commonAdapter2
        photo_list.visibility = if (photos.size > 0) View.VISIBLE else View.GONE
        commonAdapter = object : CommonAdapter<String>(this, R.layout.layout_photo_item_list, photos) {

            override fun convert(holder: ViewHolder, path: String, position: Int) {
                val photo = holder.getView<ImageView>(R.id.iv_thumb)

                GlideApp.with(this@ArchiveDetailActivity).load(path).placeholder(R.mipmap.loading).centerCrop().into(photo)
                photo.setOnClickListener {
                    Album.gallery(this@ArchiveDetailActivity)
                            .checkedList(photos)
                            .requestCode(1001) // 请求码，会在listener中返回。
                            .checkable(false) // 是否有浏览时的选择功能。
                            .onResult { requestCode, result ->
                            }
                            .onCancel { requestCode, result -> }

                            .start() // 千万不要忘记调用start()方法。
                }
            }
        }
        checkAdapter = object : CommonAdapter<RecordCheckBean>(this, R.layout.layout_check_item, checks) {

            override fun convert(holder: ViewHolder, item: RecordCheckBean, position: Int) {
                holder.getView<TextView>(R.id.tv_tips).text = "第" + (position + 1) + "次核查"
                val container = holder.getView<LinearLayout>(R.id.photo_container)
                var index = 0
                container.forEach { view: View ->
                    val imageView = view as ImageView
                    if (index < item.photos.size) {
                        val url = item.photos[index].toImageUrl()
                        GlideApp.with(this@ArchiveDetailActivity).load(url).centerCrop().into(imageView)
                        imageView.visibility = View.VISIBLE
                    } else {
                        imageView.visibility = View.GONE
                    }
//                    val photos = ArrayList<String>()
//                    item.photos.forEach { item->
//                        photos.add(item.toImageUrl())
//                    }
                    imageView.setOnClickListener {
                        Album.gallery(this@ArchiveDetailActivity)
                                .checkedList(item.photos)
                                .requestCode(1001) // 请求码，会在listener中返回。
                                .checkable(false) // 是否有浏览时的选择功能。
                                .onResult { requestCode, result ->
                                }
                                .onCancel { requestCode, result -> }

                                .start() // 千万不要忘记调用start()方法。
                    }
                    index++
                }
            }
        }
        check_container.adapter = checkAdapter

        video_content.visibility = if (!TextUtils.isEmpty(recordBean.video)) View.VISIBLE else View.GONE
        if (recordBean.videoThumb != null) {
            GlideApp.with(this@ArchiveDetailActivity).load(recordBean.videoThumb).centerCrop().into(video_thumb)
        }

        video_content.setOnClickListener {
            JZVideoPlayerStandard.startFullscreen(this,
                    JZVideoPlayerStandard::class.java,recordBean.video,"视频预览")
        }


        if (recordBean.process != null && recordBean.process!!.size > 0) {
            val adapter: QMUIItemViewsAdapter<ProcessItem, View> = object : QMUIItemViewsAdapter<ProcessItem, View>(process_layout) {
                override fun createView(parentView: ViewGroup?): View {
                    return layoutInflater.inflate(R.layout.layout_process_item, parentView, false)
                }

                override fun bind(item: ProcessItem?, view: View?, position: Int) {
                    view?.findViewById<TextView>(R.id.tv_time)?.text = HDateUtils.dateToStrLong(item!!.created_at)
                    view?.findViewById<TextView>(R.id.tv_message)?.text = item.nickname + "" + item.message
                }
            }
            recordBean.process?.forEach { it ->
                adapter.addItem(it)
            }
            adapter.setup()
        }

        photo_list.adapter = (commonAdapter)
//        if (recordBean.status > 0) {
//            btn_upload_check.visibility = View.VISIBLE
//        } else {
//            btn_upload_check.visibility = View.GONE
//        }
        btn_upload_check.setOnClickListener {
            Album.image(this) // 选择图片。
                    .multipleChoice()
                    .requestCode(10001)
                    .camera(true)
                    .columnCount(3)
                    .selectCount(8)
                    .onResult { _, result ->
                        val array = ArrayList<String>()
                        result.forEach { it ->
                            array.add(it.path)
                        }
                        val loading = getLoading("正在核查")
                        loading.show()
                        recordRep.uploadCheck(array, recordBean.record_no, object : LoadingCallback<RecordCheckBean> {
                            override fun onError(msg: String) {
                                hideLoading(loading);
                                showTips(msg, QMUITipDialog.Builder.ICON_TYPE_FAIL)
                            }

                            override fun onSuccess(t: RecordCheckBean) {
                                hideLoading(loading);
                                showTips("核查成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                                checks.add(t)
                                checkAdapter?.notifyDataSetChanged()
                            }

                            override fun onSuccess() {
                            }

                            override fun onCompleted() {
                            }

                            override fun onStart() {

                            }

                        })
                    }
                    .start()
        }

    }


    override fun initView() {
        App.appComponent.inject(this)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        top_bar.setTitle("案卷核查").setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        top_bar.addLeftImageButton(R.mipmap.ic_back, R.id.action_close).setOnClickListener({ finish() })
//        pageAdapter = TabPager(supportFragmentManager)
//        viewpager.adapter = pageAdapter
    }


    override fun initLayout() {
        setContentView(R.layout.activity_record_detail)
    }

}
